// pages/history/history.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    historyArray: [],
    "current": 1,
    "pageSize": 10,
    "sortField": "createTime",
    "sortOrder": "ascend",
    tipsWithoutHistory:'加载投递历史中...'
  },
  scrollToButtom(){
    console.log('test')
  },
  /**
   * 用以测试投递数量不同的情况，参数填历史记录数量
   * 需要使用时解封输出历史记录语句上一行代码并填写数量
   */
  getTestData(amount) {
    const testData = {
      activity: {
        dept: {
          logo: 'https://scpic.chinaz.net/files/default/imgs/2024-08-27/13d58ad45c3b01d9_s.jpg'
        },
        title: "网络研发部2024招新"
      },
      createTime: "2024-09-12 13:06:18",
      cvFileUrl: "zhaoxin.gsdse.cn/api/file/download?fileName=cv/2024/on0B_7VvzPQokEcJlB1DeO92nmh8/C4Gir8z0-cL5p1EKsNdE30cbeecda655d94381fee89f54791c8f7.pdf",
      status: 0
    }
    const historyArray = []
    for (let i = 0; i < amount; i++) {
      historyArray.push(testData)
    }
    this.setData({
      historyArray:historyArray
    })
  },
  //获取历史记录
  getHistoryArray() {
    return new Promise((resolve, reject) => {
      const that = this
      wx.request({
        url: app.globalData.domain + '/api/activityUser/listByActivityOpenId',
        method: 'POST',
        data: {
          openId: wx.getStorageSync('openId'),
          current: that.data.current,
          pageSize: that.data.pageSize,
          sortField: that.data.sortField,
          sortOrder: that.data.sortOrder
        },
        header: {
          "token": wx.getStorageSync('token'),
          "content-type": 'application/json'
        },
        success: function (res) {
          // console.log(res.data.data)
          const newHistory = res.data.data
          const oldHistory = that.data.historyArray
          if (!newHistory.length) { //新历史记录无内容时直接返回
            getApp().showMessage("所有历史记录均已获取完毕")
            console.log("所有历史记录均已获取完毕")
            return
          }
          //将新获取的内容塞入旧数组中
          newHistory.forEach((item) => { 
            item.activity.title = that.truncateString(item.activity.title,13)
            oldHistory.push(item)
          })
          //渲染新数组，并将页数+1
          that.setData({
            historyArray: oldHistory,
            current: that.data.current + 1,
            tipsWithoutHistory:'空空如也，去探索一下吧~'
          })
          that.getTestData(10);
          console.log('历史记录', that.data.historyArray)
        }
      })
    })
  },
  //录取查询
  handleQuery(e) {
    const that = this
    const index = e.currentTarget.dataset.index
    const actData = this.data.historyArray[index]
    const properties = getApp().queryStringify({
      status: actData.status,
      deptName: actData.activity.dept.deptName
    })
    wx.navigateTo({
      url: "/pages/queryResult/queryResult?" + properties
    })
  },
  //查看附件  
  openFile(e) {
    const that = this
    const index = e.currentTarget.dataset.index
    const actData = this.data.historyArray[index]
    wx.showLoading({
      title: '打开文件中',
      mask: true
    })
    const fileName = this.getFilePathName(actData.cvFileUrl);
    // console.log(fileName)
    wx.downloadFile({
      url: "https://" + actData.cvFileUrl,
      filePath: wx.env.USER_DATA_PATH + '/' + fileName,
      header: {
        'token': wx.getStorageSync('token')
      },
      success: function (res) {
        wx.openDocument({
          filePath: wx.env.USER_DATA_PATH + '/' + fileName,
          showMenu: true,
          success: function (params) {
            console.log("打开文件成功")
            wx.hideLoading()
          },
          fail: function (params) {
            wx.showToast({
              title: '打开文件失败',
              icon: 'error'
            })
            wx.hideLoading()
          }
        })
        wx.hideLoading()
      },
      fail: function (err) {
        wx.showToast({
          title: '获取文件失败',
        })
        console.log(err)
        wx.hideLoading()
      },

    })
  },
  //获取URL中的文件名
  getFilePathName(path) {
    let pos1 = path.lastIndexOf('/');
    let pos2 = path.lastIndexOf('\\');
    let position = Math.max(pos1, pos2);
    if (position < 0)
      return path;
    else
      return path.substring(position + 1);
  },
  //切割过长的字符串
  truncateString(str, length) {  
    // 检查输入字符串长度是否超过指定长度  
    if (str.length > length) {  
      // 如果是，则返回前length-3个字符加上"..."  
      return str.substring(0, length - 3) + '...';  
    } else {  
      // 如果不是，直接返回原字符串  
      return str;  
    }  
  },
  /**
   * 生命周期函数--监听页面加载
   */
  async onLoad(options) {
    await this.getHistoryArray()
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    //更新选中的tarbar下标并且更新，不可删否则bug
    if (typeof this.getTabBar === 'function' &&
      this.getTabBar()) {
      this.getTabBar().setData({
        selectIndex: 1
      })
      console.warn('history')
    }
    //console.log(this.data)
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  async onPullDownRefresh() {
    await this.getHistoryArray()
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    this.getHistoryArray()
  },
})